<template>
  <div class="app-container">
    <!-- 查询表单 - 布局优化和tooltip -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" :label-width="queryFormLabelWidth">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input
                v-model="queryParams.categoryName"
                placeholder="请输入分类名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="voltageLevel">
            <template #label>
              <!-- 修正电压等级label，添加tooltip -->
              <el-tooltip content="如:10kV,35kV,110kV,220kV等" placement="top">
                <span>电压等级</span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.voltageLevel" placeholder="请选择电压等级" clearable style="width: 100%;">
              <el-option
                  v-for="dict in voltage_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="deviceType">
            <template #label>
              <!-- 修正设备类型label，添加tooltip -->
              <el-tooltip content="变压器/断路器/隔离开关/电缆等" placement="top">
                <span>设备类型</span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable style="width: 100%;">
              <el-option
                  v-for="dict in device_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['device:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['device:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['device:category:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['device:category:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表格 - 列宽优化和tooltip -->
    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类ID" align="center" prop="id" width="80" />
      <el-table-column label="分类名称" align="center" prop="categoryName" width="150" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="voltageLevel" width="120">
        <template #header>
          <!-- 修正电压等级列头，添加tooltip -->
          <el-tooltip content="如:10kV,35kV,110kV,220kV等" placement="top">
            <span>电压等级</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="voltage_level" :value="scope.row.voltageLevel"/>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="deviceType" width="150">
        <template #header>
          <!-- 修正设备类型列头，添加tooltip -->
          <el-tooltip content="变压器/断路器/隔离开关/电缆等" placement="top">
            <span>设备类型</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.deviceType"/>
        </template>
      </el-table-column>
      <el-table-column label="分类描述" align="center" prop="description" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:category:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:category:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改设备分类对话框 - 尺寸、布局优化和tooltip -->
    <el-dialog :title="title" v-model="open" width="960px" append-to-body>
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="voltageLevel">
              <template #label>
                <!-- 修正电压等级label，添加tooltip -->
                <el-tooltip content="如:10kV,35kV,110kV,220kV等" placement="top">
                  <span>电压等级</span>
                </el-tooltip>
              </template>
              <el-select v-model="form.voltageLevel" placeholder="请选择电压等级" style="width: 100%;">
                <el-option
                    v-for="dict in voltage_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="deviceType">
              <template #label>
                <!-- 修正设备类型label，添加tooltip -->
                <el-tooltip content="变压器/断路器/隔离开关/电缆等" placement="top">
                  <span>设备类型</span>
                </el-tooltip>
              </template>
              <el-select v-model="form.deviceType" placeholder="请选择设备类型" style="width: 100%;">
                <el-option
                    v-for="dict in device_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">设备基本信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddDeviceInfo">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteDeviceInfo">删除</el-button>
          </el-col>
        </el-row>
        <!-- 子表格 - 列宽优化和tooltip，并设置max-height -->
        <el-table :data="deviceInfoList" :row-class-name="rowDeviceInfoIndex" @selection-change="handleDeviceInfoSelectionChange" ref="deviceInfo" max-height="300px">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column label="设备名称" prop="deviceName" width="120" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.deviceName" placeholder="请输入设备名称" />
            </template>
          </el-table-column>
          <el-table-column label="设备型号" prop="model" width="100" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.model" placeholder="请输入设备型号" />
            </template>
          </el-table-column>
          <el-table-column label="设备规格" prop="specification" width="120" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.specification" placeholder="请输入设备规格" />
            </template>
          </el-table-column>
          <el-table-column label="制造商" prop="manufacturer" width="100" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.manufacturer" placeholder="请输入制造商" />
            </template>
          </el-table-column>
          <el-table-column label="供应商" prop="supplier" width="100" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.supplier" placeholder="请输入供应商" />
            </template>
          </el-table-column>
          <el-table-column label="采购时间" prop="purchaseDate" width="160">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.purchaseDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="安装位置" prop="location" width="120" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.location" placeholder="请输入安装位置" />
            </template>
          </el-table-column>
          <el-table-column prop="status" width="120">
            <template #header>
              <!-- 修正设备状态列头，添加tooltip -->
              <el-tooltip content="0-停用,1-启用,2-维修中,3-报废" placement="top">
                <span>设备状态</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态">
                <el-option
                    v-for="dict in device_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <!-- 假设增加一个设备描述字段，用于展示长文本 -->
          <el-table-column label="设备描述" prop="description" min-width="150" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.description" type="textarea" :rows="1" placeholder="请输入描述" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category">
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/device/category"

const { proxy } = getCurrentInstance()
// 确保字典值正确引入
const { device_status, voltage_level, device_type } = proxy.useDict('device_status', 'voltage_level', 'device_type')

const categoryList = ref([])
const deviceInfoList = ref([]) // 子表数据
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedDeviceInfo = ref([]) // 子表选中项
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const queryFormLabelWidth = ref('80px'); // 默认值

const data = reactive({
  form: {
    // 确保deviceInfoList在form中初始化
    deviceInfoList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryName: null,
    voltageLevel: null,
    deviceType: null,
    description: null,
  },
  rules: {
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    deviceType: [
      { required: true, message: "设备类型不能为空", trigger: "change" }
    ],
    // createTime 和 updateTime 通常由后端自动维护，无需前端校验
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询设备分类列表 */
function getList() {
  loading.value = true
  listCategory(queryParams.value).then(response => {
    categoryList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    categoryName: null,
    voltageLevel: null,
    deviceType: null,
    description: null,
    sort: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    deviceInfoList: [] // 重置时清空子列表
  }
  deviceInfoList.value = [] // 确保响应式变量也重置
  proxy.resetForm("categoryRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备分类"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset() // 先重置，再加载数据
  const _id = row.id || ids.value
  getCategory(_id).then(response => {
    form.value = response.data
    // 确保从后端返回的deviceInfoList是数组
    deviceInfoList.value = response.data.deviceInfoList || []
    open.value = true
    title.value = "修改设备分类"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {
      form.value.deviceInfoList = deviceInfoList.value
      if (form.value.id != null) {
        updateCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除设备分类编号为"' + _ids + '"的数据项？').then(function() {
    return delCategory(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 设备基本信息序号 */
function rowDeviceInfoIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 设备基本信息添加按钮操作 */
function handleAddDeviceInfo() {
  let obj = {
    deviceName: "",
    model: "",
    specification: "",
    manufacturer: "",
    supplier: "",
    purchaseDate: "",
    location: "",
    status: "",
    description: "" // 添加设备描述字段供演示
  }
  deviceInfoList.value.push(obj)
}

/** 设备基本信息删除按钮操作 */
function handleDeleteDeviceInfo() {
  if (checkedDeviceInfo.value.length === 0) {
    proxy.$modal.msgError("请先选择要删除的设备基本信息数据")
  } else {
    // 过滤掉选中的行，并重新为剩余行设置索引
    deviceInfoList.value = deviceInfoList.value.filter(item => !checkedDeviceInfo.value.includes(item.index));
    // 清空选中项
    checkedDeviceInfo.value = [];
    // 强制刷新表格选中状态，确保UI同步
    proxy.$nextTick(() => {
      proxy.$refs.deviceInfo.clearSelection();
    });
  }
}

/** 复选框选中数据 */
function handleDeviceInfoSelectionChange(selection) {
  checkedDeviceInfo.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device/category/export', {
    ...queryParams.value
  }, `category_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
/* 可以在这里添加一些样式来微调布局，例如： */
.el-row {
  margin-bottom: 10px; /* 增加行之间的间距，保持视觉平衡 */
}
.el-form-item {
  margin-bottom: 0; /* 在el-row中已经有间距，减少form-item自带的冗余间距 */
}
</style>

